package com.wch.user.service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import util.IdWorker;

import com.wch.user.dao.UserDao;
import com.wch.user.pojo.User;

/**
 * user服务层
 * 
 * @author Administrator
 *
 */
@Service
@SuppressWarnings("all")
public class UserService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private IdWorker idWorker;

	//add by WanChengHe 20190417
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private BCryptPasswordEncoder encoder;


	/**
	 * 增加用户
	 * @param user 用户
	 * @param code 用户填写的验证码
	 */
	public void add(User user,String code){
		//判断验证码是否正确
		String syscode = (String)redisTemplate.opsForValue().get("smscode_"+user.getMobile());

	/*	if(null == syscode){        //验证码过期
			throw  new RuntimeException("请点击获取短信验证码");
		}

		if(!syscode.equals(code)){    //验证码不对
			throw  new RuntimeException("验证码输入不正确");
		}*/

		user.setId(idWorker.nextId()+"");
		user.setFollowcount(0);  //关注数
		user.setFanscount(0);  //粉丝数
		user.setOnline(0L);   //在线时长
		user.setRegdate(new Date());  //注册日期
		user.setUpdatedate(new Date());  //更新日期
		user.setLastdate(new Date());   //最后登录日期

		//modify by WanChengHe 20190425 添加密码加密的处理逻辑
		String newPassword = encoder.encode(user.getPassword());  //加密后的密码字符串
		user.setPassword(newPassword);

		userDao.save(user);
	}


	/**
	 * 发送短信验证码
	 * @param mobile 手机号码
	 * @Date add by WanChengHe 20190417
	 */
	public void sendSms(String mobile){
		//1:生成六位数短信验证码，看需要，四位或者六位都可以，根据自己的需要
		Random random = new Random();
		int max = 999999;   //最大数
		int min = 100000;  //最小数
		int code = random.nextInt(max); //获取随机数，【0，max）
		if(code < min){
			code +=min;
		}
		System.out.println(mobile+"收到的验证码是："+code);

		//2：将生成的验证码放入redis中，像我们平时短信验证码一般都有时间限制，验证码多少分钟过期，所以要设置redis过期时间
		redisTemplate.opsForValue().set("smscode_"+mobile,code+"",2, TimeUnit.MINUTES);  //设置两分钟过期

		//3：将验证码和手机号放入rabbitMQ中，待后面消费者消费
		Map<String,String> map = new HashMap<>();
		map.put("mobile",mobile);
		map.put("code",code+"");
		rabbitTemplate.convertAndSend("sms",map);
	}
	/**
	 * 查询全部列表
	 * @return
	 */
	public List<User> findAll() {
		return userDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<User> findSearch(Map whereMap, int page, int size) {
		Specification<User> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return userDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<User> findSearch(Map whereMap) {
		Specification<User> specification = createSpecification(whereMap);
		return userDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	public User findById(String id) {
		return userDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param user
	 */
	public void add(User user) {
		// user.setId( idWorker.nextId()+"" ); 雪花分布式ID生成器
		userDao.save(user);
	}

	/**
	 * 修改
	 * @param user
	 */
	public void update(User user) {
		userDao.save(user);
	}

	/**
	 * 删除
	 * @param id
	 */
	public void deleteById(String id) {
		userDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<User> createSpecification(Map searchMap) {

		return new Specification<User>() {

			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // ID
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 手机号码
                if (searchMap.get("mobile")!=null && !"".equals(searchMap.get("mobile"))) {
                	predicateList.add(cb.like(root.get("mobile").as(String.class), "%"+(String)searchMap.get("mobile")+"%"));
                }
                // 密码
                if (searchMap.get("password")!=null && !"".equals(searchMap.get("password"))) {
                	predicateList.add(cb.like(root.get("password").as(String.class), "%"+(String)searchMap.get("password")+"%"));
                }
                // 昵称
                if (searchMap.get("nickname")!=null && !"".equals(searchMap.get("nickname"))) {
                	predicateList.add(cb.like(root.get("nickname").as(String.class), "%"+(String)searchMap.get("nickname")+"%"));
                }
                // 性别
                if (searchMap.get("sex")!=null && !"".equals(searchMap.get("sex"))) {
                	predicateList.add(cb.like(root.get("sex").as(String.class), "%"+(String)searchMap.get("sex")+"%"));
                }
                // 头像
                if (searchMap.get("avatar")!=null && !"".equals(searchMap.get("avatar"))) {
                	predicateList.add(cb.like(root.get("avatar").as(String.class), "%"+(String)searchMap.get("avatar")+"%"));
                }
                // E-Mail
                if (searchMap.get("email")!=null && !"".equals(searchMap.get("email"))) {
                	predicateList.add(cb.like(root.get("email").as(String.class), "%"+(String)searchMap.get("email")+"%"));
                }
                // 兴趣
                if (searchMap.get("interest")!=null && !"".equals(searchMap.get("interest"))) {
                	predicateList.add(cb.like(root.get("interest").as(String.class), "%"+(String)searchMap.get("interest")+"%"));
                }
                // 个性
                if (searchMap.get("personality")!=null && !"".equals(searchMap.get("personality"))) {
                	predicateList.add(cb.like(root.get("personality").as(String.class), "%"+(String)searchMap.get("personality")+"%"));
                }
				
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}

	/**
	 * 密码校验
	 * add by WanChengHe 20190425
	 * @param mobile
	 * @param password
	 * @return
	 */
	public User findByMobileAndPassword(String mobile,String password){
		User user = userDao.findByMobile(mobile);

		if (null != user && encoder.matches(password,user.getPassword())){
			return user;
		}else{
			return null;
		}
	}
}
